package common

import (
	"net"
	"net/http"
	"net/http/cookiejar"
	"net/url"
	"time"
)

type SpiderTransport struct {
	Transport http.RoundTripper
	config    *SpiderConfig
}

func (self *SpiderTransport) transport() http.RoundTripper {
	var dialer *net.Dialer = &net.Dialer{}
	if self.config != nil {
		if self.config.TIMEOUT <= 0 && self.config.TIMEOUT > time.Second*60 {
			self.config.TIMEOUT = _DEFAULT_TIMEOUT
		}
		dialer.Timeout = self.config.TIMEOUT
		if self.config.ENABLE_KEEPALIVE {
			dialer.KeepAlive = self.config.KEEPALIVE
		}
	}
	transport := &http.Transport{
		Proxy:               http.ProxyFromEnvironment,
		Dial:                (dialer).Dial,
		TLSHandshakeTimeout: 10 * time.Second,
	}
	if self.config != nil {
		transport.DisableCompression = !self.config.ENABLE_COMPRESSION
		if self.config.ENABLE_PROXY && self.config.PROXY_SERVER_SERVER != "" {
			u, err := url.Parse(self.config.PROXY_SERVER_SERVER)
			if err == nil {
				//logger.Info("use proxy:%s", self.config.PROXY_SERVER_SERVER)
				proxy := http.ProxyURL(u)
				transport.Proxy = proxy
			} else {
				//logger.Error("use proxy:%s", err)
			}
		}

	}
	self.Transport = transport
	return self.Transport
}

func (self *SpiderTransport) RoundTrip(req *http.Request) (*http.Response, error) {
	//req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:30.0) Gecko/20100101 Firefox/30.0")
	return self.transport().RoundTrip(req)
}
func (self *SpiderTransport) Client() *http.Client {
	client := &http.Client{Transport: self}
	if self.config != nil && self.config.ENABLE_COOKIE {
		jar, err := cookiejar.New(nil)
		if err == nil {
			client.Jar = jar
		}
	}
	return client
}
